<template>
  <el-form
    ref="formRef"
    :model="formData"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <el-table :data="formData" class="-mt-10px">
      <el-table-column label="序号" type="index" width="80" align="center" />
      <el-table-column label="产品名称" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.productName`"
            class="mb-0px!"
          >
            <el-input v-model="row.productName" disabled />
          </el-form-item>
        </template>
      </el-table-column>
      <!-- 加批次列 -->
      <!-- <el-table-column label="批次" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.productBatch`"
            class="mb-0px!"
          >
            <el-input v-model="row.productBatch" disabled />
          </el-form-item>
        </template>
      </el-table-column> -->
      <el-table-column label="产品单位名" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.productUnitName`"
            class="mb-0px!"
          >
            <el-input v-model="row.productUnitName" disabled />
          </el-form-item>
        </template>
      </el-table-column>
      <!-- 库存数量 -->
      <el-table-column label="库存数量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.count`" class="mb-0px!">
            <el-input v-model="row.repertoryCount" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="核销数量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.count`" class="mb-0px!">
            <el-input v-model="row.count" disabled />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.remark`" class="mb-0px!">
            <el-input v-model="row.remark" disabled />
          </el-form-item>
        </template>
      </el-table-column>
      
      <!-- 有效期 -->
      <el-table-column label="有效期" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.productValidityDate`"
            class="mb-0px!"
          >
            <el-date-picker
              v-model="row.productValidityDate"
              type="date"
              placeholder="请选择有效期"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link disabled>—</el-button>
        </template>
      </el-table-column> -->
    </el-table>
  </el-form>
  <!-- <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round disabled>+ 添加ERP 核销报废管理单项</el-button>
  </el-row> -->
</template>
<script setup lang="ts">
import { CheckOutApi } from '@/api/erp/checkout'
import { SecStockApi } from '@/api/erp/secstock'
import { it } from 'node:test'

const props = defineProps<{
  outId: undefined // 出库编号（主表的关联字段）
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRef = ref() // 表单 Ref
const productOptions = ref([])
let type = ([90,91])

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.outId,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return
    }
    try {
      formLoading.value = true
      formData.value = await CheckOutApi.getCheckOutItemListByOutId(val)
      // console.log('formdata', formData.value)
      productOptions.value = await SecStockApi.getSecStockListByDeptId(type)
      // console.log('productOptions', productOptions.value)
      // 更新 formData 中的库存数量
      formData.value.forEach((item) => {
        updateRowWithSelectedProduct(item)
      })
    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)

// 更新行数据
const updateRowWithSelectedProduct = (row: any) => {
  const selectedProducts = productOptions.value.filter((product) => product.productId === row.productId);
  // console.log("selectedProducts：", selectedProducts);
  if (selectedProducts.length > 0) {
    row.productUnitName = selectedProducts[0].productUnitName;
    row.productName = selectedProducts[0].productName;

    // 计算所有匹配项的 count 总和
    row.repertoryCount = selectedProducts.reduce((sum, product) => sum + product.count, 0);

    // 如果需要处理批次、有效期等信息，可以在这里进行相应的逻辑处理
    // 例如，这里假设取第一个匹配项的批次和有效期
    row.productValidityDate = selectedProducts[0].productValidityDate;
  }
}

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    outId: undefined,
    productId: undefined,
    productUnitId: undefined,
    count: undefined,
    remark: undefined,
    productBatch: undefined,
    productValidityDate: undefined,
    repertoryCount: undefined
  }
  row.outId = props.outId
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

defineExpose({ validate, getData })
</script>